import React from "react"
import {Modal, Form, Select, Button, Radio,} from 'antd'
import FunReturnVo from './FunReturnVo'
import $ from 'jquery';   //加载jQuery

import {fileListApi, modifyFunctionApi} from "../api/projectConfig"
import {getVoPrefixAndPostfix} from "../utils/CommUtil";
import {Config} from "../utils/Constants";

var RadioButton = Radio.Button;
var RadioGroup = Radio.Group;
const Option = Select.Option
const FormItem = Form.Item

class ControllerFunReturn extends React.Component {

    state = {
        visible: false,
        vOVisible: false,
        pageList: [],
        voList: [],
        argTypeName: 'vo',

        _clickObj: {},
        _parentVo: {},

        resPageId: null,
        resVoId: null,

        returnVo: {},

        dataTypeObjList: [], // 对象选择
        // dataType: base table vo
        resObj: {
            "dataType": "base",
            "name": "BaseRes",
            "id": 3,
            "collectionType": "single",
            "paradigm": "yes",
            "next": {
                "dataType": "base",
                "name": "CommentResult",
                "id": 8,
                "collectionType": "single",
                "paradigm": "yes",
                "next": {"name": "UserVo", "id": 8, "collectionType": "single", "paradigm": "no"}
            }
        }

    }

    funInfo = {}
    voShowCallBack // 设置返回参 回调

    resType = [{key: 'void', label: 'void 无返回'},
        {key: 'vo', label: 'Vo 对象类型'},
        {key: 'page', label: 'Page 页面'},
        {key: 'file', label: 'File 下载文件'},
        {key: 'img', label: 'Img 图片流'},
        {key: 'string', label: 'String'},
    ]

    /** 选择VO */

    constructor(props) {
        super(props)
    }

    componentDidMount() {
        this.props.onRef(this)
    }

    fetchVoList = async () => {
        let fileListList = await fileListApi(this.props.projectId, 'vo');
        return fileListList.data.data;
    }

    handleCancel = () => {
        this.setState({...this.state, visible: false})
    }

    show = async (funInfo, voShowCallBack) => {
        this.voShowCallBack = voShowCallBack
        this.funInfo = funInfo
        var _resObj = funInfo.returnVo
        if (_resObj) {
            _resObj = JSON.parse(_resObj)
        } else {
            _resObj = {} // 无时为空
        }
        let _resVoId = funInfo.resVoId

        let initObj = {
            returnVo: _resObj,
            resObj: _resObj,
            resVoId: _resVoId,
            resType: funInfo.resType,
            resPageId: funInfo.resPageId
        }
        _resObj.dataType = _resObj.dataType ? _resObj.dataType : 'vo';

        this.changeReturnDataType(_resObj.dataType);
        this.setState({...this.state, ...initObj, visible: true})

    }

    handleOk = () => {


        let getVoShow = (resObj) => {

            let {prefix, postfix} = getVoPrefixAndPostfix(resObj)

            var name = prefix + (resObj.name ? resObj.name : '') + postfix
            if (resObj.next || resObj.paradigm == 'yes') {
                name = name + '<' + getVoShow(resObj.next) + '>';
            }
            return name;
        }


        let postObj = {resType: this.state.argTypeName, id: this.funInfo.id}
        if (postObj.resType == 'vo' || postObj.resType == 'page') {

            let returnShow = getVoShow(this.state.resObj);

            // 还需加上 主VO
            let newArray = this.state.voList.filter(item => item.id == this.state.resVoId)
            var _nowObj = newArray[0]
            if (_nowObj.paradigm == 'yes') {
                let {prefix, postfix} = getVoPrefixAndPostfix(_nowObj)
                postObj['returnShow'] = _nowObj.name + '<' + prefix + returnShow + postfix + '>';
            }

            postObj['resVoId'] = this.state.resVoId;
            postObj['returnVo'] = JSON.stringify(this.state.resObj);

            if (this.state.resType == 'page') {
                postObj['resPageId'] = this.state.resPageId;
            }

        }

        modifyFunctionApi(postObj).then(res => {
            this.voShowCallBack(postObj.returnShow)
        })

        this.setState({...this.state, visible: false})
    }

    argTypeHandleChange = (value) => {
        console.info('argType=' + value)

        this.setState({
            ...this.state,
            argTypeName: value
        })
    }

    voSelectHandleCancel = () => {
        this.setState({...this.state, vOVisible: false})
    }


    /** 跟据 dataType显示下接框内容 */
    changeReturnDataType = async (dataType) => {
        this.state.resObj.dataType = dataType;
        if (dataType == 'vo') {
            // fetch vo list
            let _voList = await this.fetchVoList();
            this.setState({...this.state, dataTypeObjList: _voList, voList: _voList});
        } else if (dataType == 'base') {
            var arr = [];
            Config.DATA_TYPE_LIST.map((val, index) => {
                arr.push({name: val, dataType});
            });
            this.setState({...this.state, dataTypeObjList: arr});
        } else if (dataType == 'table') {
            // refresh table
        }
    }


    render() {


        const formItemLayout = {
            labelCol: {
                sm: {span: 4},
            },
            wrapperCol: {
                sm: {span: 18},
            },
        }

        return (<Modal
            key='controllerfunReturn'
            width={800}
            visible={this.state.visible}
            keyboard={false}
            maskClosable={false}
            title="params"
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            footer={[
                <Button type="primary" onClick={this.handleOk} key='controllerfunReturn_save' htmlType="submit"
                        icon="save">确定</Button>,
                <Button key="back" onClick={this.handleCancel}>关闭</Button>
            ]}
        >

            <Form className="form_item_4" onSubmit={() => {
            }}>

                <FormItem {...formItemLayout} label="对象类型">

                    <Select value={this.state.argTypeName} onChange={this.argTypeHandleChange} style={{width: '200px'}}
                            placeholder="对象类型">
                        {this.resType.map((vo, index) => <Option key={vo.key}>{vo.label}</Option>)}
                    </Select>

                </FormItem>

                {
                    this.state.argTypeName == 'page'
                        ?
                        <FormItem {...formItemLayout} label="Page-页面">
                            <Select onChange={this.argTypeHandleChange} style={{width: '200px'}} placeholder="Page-页面">
                                {this.state.pageList.map((vo, index) => <Option key={vo.key}>{vo.label}</Option>)}
                            </Select>
                        </FormItem>
                        : ''
                }

                {
                    this.state.argTypeName == 'page' || this.state.argTypeName == 'vo'
                        ?
                        <FormItem {...formItemLayout} label="VO-对象">
                            <Select value={this.state.resVoId} onChange={(val) => {

                                let returnVo = this.state.voList.filter(item => item.id == val)[0]
                                this.setState({...this.state, returnVo: returnVo, resVoId: val})
                            }} style={{width: '280px'}} placeholder="VO-对象">
                                {this.state.voList.map((vo, index) => <Option key={'vo_type_' + vo.id} value={vo.id}>{vo.name}</Option>)}
                            </Select>
                        </FormItem>
                        : ''
                }

                {
                    /** 范型 */

                    this.state.returnVo.paradigm == 'yes' || (this.funInfo.returnShow && this.funInfo.returnShow.indexOf('<')) > 0 && (this.state.argTypeName == 'page' || this.state.argTypeName == 'vo')
                        ?
                        <FormItem {...formItemLayout} label="T类型">
                            <FunReturnVo parentVo={{}} resObj={this.state.resObj}
                                         onSelectVo={(_parentVo, _clickObj) => {
                                             this.setState({
                                                 ...this.state,
                                                 _clickObj: _clickObj,
                                                 _parentVo: _parentVo,
                                                 vOVisible: true
                                             })
                                         }} key={'FunReturnVo_key_' + this.state.resObj.id}></FunReturnVo>
                        </FormItem>
                        :
                        ''
                }

            </Form>

            {/* 选择T对应的VO */}
            <Modal
                key='controllerfunReturnSetting'
                width={800}
                visible={this.state.vOVisible}
                keyboard={false}
                maskClosable={false}
                title="params"
                onCancel={this.voSelectHandleCancel}
                footer={[
                    <Button onClick={() => {

                        // 最后一级的next等于选中对象
                        var obj = this.state._parentVo
                        while (obj.next) {
                            obj = obj.next
                        }
                        obj.next = this.state._clickObj

                        //console.info('this.state._parentVo=' + JSON.stringify(this.state._parentVo))

                        this.setState({...this.state, resObj: this.state._parentVo.next, vOVisible: false})

                    }} type="primary" key='controllerfunReturn_setting_save' icon="save">确定</Button>,
                    <Button key="back" onClick={this.voSelectHandleCancel}>关闭</Button>
                ]}
            >

                <Form className="form_item_4" onSubmit={() => {

                }}>

                    {/** 基本数据类型/数据库表/vo */}
                    <FormItem {...formItemLayout} label="类型选择">
                        <RadioGroup defaultValue="vo" value={this.state.resObj.dataType} onChange={(e) => {

                            let dataType = e.target.value;
                            console.info('value=' + dataType);

                            /** 跟据 dataType显示下接框内容 */
                            this.changeReturnDataType(dataType);

                        }}>
                            <RadioButton value="base">base</RadioButton>
                            <RadioButton value="table">table</RadioButton>
                            <RadioButton value="vo">vo</RadioButton>
                        </RadioGroup>
                    </FormItem>

                    <FormItem {...formItemLayout} label="对象">

                        {/** vo/base/table 类型数据 */}
                        <Select style="float:left"
                                value={this.state._clickObj.id ? this.state._clickObj.id : this.state._clickObj.name}
                                onChange={(val) => {

                                    console.info('val=' + val);

                                    var dataType = this.state.resObj.dataType;

                                    if (dataType == 'vo') {
                                        var _nowObj = this.state.dataTypeObjList.filter(item => item.id == val)[0];

                                        if (this.state._clickObj.collectionType) {
                                            _nowObj.collectionType = this.state._clickObj.collectionType
                                        }

                                        let {name, id, collectionType, paradigm} = _nowObj
                                        _nowObj = {name, id, collectionType, paradigm}

                                        this.setState({...this.state, _clickObj: _nowObj})
                                    } else if (dataType == 'base') {
                                        var _nowObj = this.state.dataTypeObjList.filter(item => item.name == val)[0];
                                        _nowObj.dataType = 'base';
                                        this.setState({...this.state, _clickObj: _nowObj})
                                    }
                                    /*
                                    let newArray = this.state.voList.filter(item => item.id == val)
                                    var _nowObj = newArray[0]

                                    if (this.state._clickObj.collectionType) {
                                        _nowObj.collectionType = this.state._clickObj.collectionType
                                    }

                                    let {name, id, collectionType, paradigm} = _nowObj
                                    _nowObj = {name, id, collectionType, paradigm}


                                    this.setState({...this.state, _clickObj: _nowObj})
                                    */
                                }} style={{width: '280px'}} placeholder="VO-对象">
                            {this.state.dataTypeObjList.map((vo, index) => <Option key={'vo_type_' + vo.id}
                                                                                   value={vo.id ? vo.id : vo.name}>{vo.name}</Option>)}
                        </Select>


                        <span style={{display: 'inline-block', width: '100%'}}>
                        <Radio.Group onChange={(e) => {

                            this.state._clickObj.collectionType = e.target.value

                            this.setState({...this.state, _clickObj: this.state._clickObj})

                        }} value={this.state._clickObj.collectionType || 'single'}>
                            <Radio value="single">单值</Radio>
                            <Radio value="list">List</Radio>
                            <Radio value="map">Map</Radio>
                            <Radio value="set">Set</Radio>
                        </Radio.Group>
                        </span>
                    </FormItem>
                </Form>

            </Modal>

        </Modal>)
    }
}

export default ControllerFunReturn
